/***
must import jquery.validate.min.js before import me
and jquery and jquery-ui that in font of me
**/
$(function(){
	$.validator.setDefaults({
		errorPlacement:function(error,element) {
			error = initErrLabel(error);
			var eleTagName = element.attr("type");
			if(eleTagName=="radio" || eleTagName=="checkbox"){ 
				if(element.parent().is("span") && element.parent().parent().is("div.factor")){
					element.parent().parent().append(error);
				}else if(element.parent().is("div.divSpan")){ //等保
					element.parent().parent().append(error);
					error.wrap("<div class=\"divSpan\"></div>");
				}else{
					error.insertAfter(element);
				}
			}else{
				error.insertAfter(element);
			}
	    },success:function(label){
	    	if(typeof(beforeSuccess)=="function") beforeSuccess(label);
	    	
        	var errTarget = $("#"+label.attr("for"));
        	label.removeClass("errico").attr("title","");
        	errTarget.removeClass("ui-state-error errTarget");
        	
        	if(typeof(afterSuccess)=="function") afterSuccess(label);
        	
        },showErrors:function(errorMap,errorList){
	    	if(typeof(beforeShowErrors)=="function") beforeShowErrors(errorMap,errorList);
	    	this.defaultShowErrors();
	    	if(typeof(afterShowErrors)=="function") afterShowErrors(errorMap,errorList);
	    	$.each(errorList, function(i,n){
        		var errTarget = $(n.element);
        		var errLabel = errTarget.next("label.error");
        		var eleTagName = errTarget.attr("type");
    			if(eleTagName=="radio" || eleTagName=="checkbox"){
    				if(errTarget.parent().is("span") && errTarget.parent().parent().is("div.factor")){
    					errLabel = errTarget.parent().parent().children("label.error").first();
    				}else if(errTarget.parent().is("div.divSpan")){ //等保
    					errLabel = errTarget.parent().parent().find("div.divSpan label.error:first-child").first();
    				}
    				
    			}
        		if($.trim(errLabel.text()).length>0){
        			errTarget.addClass("ui-state-error errTarget");
        			errLabel.addClass("errico").attr("title",errLabel.text()).text("");
        		}
        	});
	    	if(typeof(lastShowErrors)=="function") lastShowErrors(errorMap,errorList);
	    }
	});
});

function initErrLabel(label){
	var errorText = label.text();
	var errTarget = $("#"+label.attr("for"));
	label.removeClass("errico");
	errTarget.removeClass("ui-state-error").removeClass("errTarget");
	if(errTarget){
		errTarget.addClass("ui-state-error").addClass("errTarget");
		label.text("").addClass("errico").attr("title",errorText);
		bindToolTip(label);
	}
	
	return label;
}

function bindToolTip(label){
	try{label.tooltip("destroy");}catch(e){}
	label.tooltip({
		position:{my: "left bottom-2",at: "left top"}, 
		tooltipClass: "custom-tooltip"
	});
}
